'use strict';
$(function () {
    yams.menu.select('couponManagement');

    yams.page = {
        /**
         * 初始化页面
         */
        init: function () {
            this.initDataList();
            this.initCouponStaticsList();
            this._couponList = this.couponList('#couponList', false);
            this.initUserList();
            this.initEvent();
            Dolphin.form.parse();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;

            //新建券模型
            $(".newData").click(function () {
                Dolphin.form.empty('.edit-form');
                $('#dataModal').modal('show');
            });

            //查看券使用情况
            $(".couponDatas").click(function () {
                $('#couponModal').modal('show');
            });


            $(".modelSave").click(function () {
                let ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');

                    var startDateStr = $("#startDate").val();
                    var endDateStr = $("#endDate").val();
                    if(startDateStr == '' || endDateStr == ''){
                        Dolphin.alert("有效时间段不能为空！");
                        return;
                    }
                    data.startDate = data.startDate+' 00:00:00';
                    data.endDate = data.endDate+' 23:59:59';

                    Dolphin.ajax({
                        url: '/api/0321a98b44054407b45038df79e4eaa2',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._dataList.load();
                            $('#dataModal').modal('hide');
                        }
                    });

                }
            });

            /**
             *  确定生成券
             */
            $(".confirmBtn").click(function () {
                let ef = $(".generate-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    let couponmsg = $("#showMsg").text();
                    let couponcnt = $("#couponCnt").val();
                    console.log(data);
                    Dolphin.confirm('确定生成' + couponcnt + '张' + couponmsg + '吗？', {
                        callback: function (flag) {
                            if (flag) {
                                var paramData = {};
                                paramData.properties = data;
                                Dolphin.ajax({
                                    url: '/api/972eb264bcae478c9cbf182cef0aaa1d',
                                    type: Dolphin.requestMethod.PUT,
                                    data: Dolphin.json2string(paramData),
                                    onSuccess: function () {
                                        $('#generateModal').modal('hide');
                                        $('#couponModelModal').modal('hide');
                                        me._dataList.reload();
                                    }
                                });
                            }
                        }
                    });
                }

            });

            //券模型查询
            $(".btn-query").click(function () {
                let d = Dolphin.form.getValue('.query-form');
                me._dataList.query(d);
            });

            //券查询
            $("#queryCoupon").click(function () {
                let d = Dolphin.form.getValue('.query-coupon-form');
                me._couponStaticsList.query(d);
            });

            $("#couponType").change(function () {
                if('CT01' == $(this).val()){//现金
                    $("#couponValDiv").show();
                    $("#couponValLabel").html('优惠金额');
                    $("#couponValUnit").html('元');

                }else if('CT02' == $(this).val()){//折扣
                    $("#couponValDiv").show();
                    $("#couponValLabel").html('优惠折扣');
                    $("#couponValUnit").html('%');
                }else{ // 请选择
                    $("#couponValDiv").hide();
                    $("#couponVal").val("");

                }
            });

            //选定会员发放券
            $(".confirmUser").click(function(){
                let userArray = me._userList.getChecked();
                $("#userId").val(userArray[0].id);
                $('#userModal').modal('hide');

                let condition = Dolphin.form.getValue('.dilivery-form');
                //发放券
                    Dolphin.ajax({
                        url: '/api/c2bf65dc802b40778890b500f258acfd',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({'properties' : condition}),
                        onSuccess: function (reData) {
                            console.log(reData);
                            me._dataList.load();
                            me._couponList.empty();
                        }
                    });
                });

        },

        initDataList: function () {
            let me = this;
            me._dataList = new Dolphin.LIST({
                panel: "#dataList",
                title:'券模型列表',
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: '券名称'
                },  {
                    code: 'couponType',
                    title: '券类型',
                    formatter: function(val, row, index){
                        return Dolphin.enum.getEnumText("couponType", val);
                    }
                },{
                    code: 'couponVal',
                    title: '券优惠',
                    formatter: function(val, row, index){
                        if(row.couponType == 'CT01'){
                            return val + '元';
                        }else if(row.couponType == 'CT02'){
                            return val + '%';
                        }else{
                            return '无';
                        }
                    }
                }, {
                    code : 'startDate',
                    title : '有效开始时间',
                    formatter : function(val, row, index){
                        return val.substr(0,10);
                    }
                },{
                    code : 'endDate',
                    title : '有效截至时间',
                    formatter : function(val, row, index){
                        return val.substr(0,10);
                    }
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '90px',
                    formatter: function (val, row, index) {
                        //生成券按钮
                        var generateBtnStr = '<a class="btn btn-outline btn-circle btn-sm blue generateBtn" ' +
                            'href="javascript:;" data-id="'+row.id+'">' +
                            '<i class="fa fa-envelope-o"></i>生成</a>';
                        //编辑按钮
                        var editBtnStr = yams.buttons.edit({
                            id: row.id
                        });
                        //发放券按钮
                        var diliveryBtnStr = '<a class="btn btn-outline btn-circle btn-sm green diliveryBtn" ' +
                            'href="javascript:;" data-id="'+row.id+'" data-name="'+row.name+'">' +
                            '<i class="fa fa-paper-plane"></i>发放</a>';

                        return  generateBtnStr + editBtnStr + diliveryBtnStr;
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/0321a98b44054407b45038df79e4eaa2',
                pagination: true,
                onClick: function (data, thisRow, event) {
                    console.log(data)
                    me._couponList.loadData({rows: data.couopons});
                },
                onLoadSuccess: function () {
                    //编辑
                    yams.buttons.editCallback('c9abd99f6b5843849eda6d9a205a0bac', 'id', function (reData) {
                        $('#dataModal').modal('show');
                    });

                    //生成券
                    $(".generateBtn").click(function(){
                        var _this = $(this);
                        Dolphin.ajax({
                            url: '/api/c9abd99f6b5843849eda6d9a205a0bac@id=' + _this.data('id'),
                            type: Dolphin.requestMethod.GET,
                            onSuccess: function (reData) {
                                if(reData && reData.value) {
                                    reData.value.couponCnt = reData.value.properties.userTotal;
                                    Dolphin.form.setValue(reData.value, '.generate-form');
                                    $('#generateModal').modal('show');
                                    me._dataList.load();
                                }
                            }
                        });

                    });

                    //发放券
                    $(".diliveryBtn").click(function(){
                        var _this = $(this);
                        //检查有多少可发放的券，有多少会员
                        var paramData = {};
                        paramData.properties = { 'couponModel_id_obj_ae' : _this.data('id'),
                                                 'status' : 1};
                        Dolphin.ajax({
                            url: '/api/b588e1ce53b9472897e1ce7311db5a82',
                            type: Dolphin.requestMethod.POST,
                            data: Dolphin.json2string(paramData),
                            onSuccess: function (reData) {
                                console.log(reData);
                                Dolphin.confirm('确定对所有会员发放'+_this.data('name')
                                    +'吗？（券数量：'+reData.value.properties.couponTotal
                                    +'，会员数量：'+reData.value.properties.userTotal+'）', {
                                    callback: function (flag) {
                                        if (flag) {
                                            var paramData = {};
                                            paramData.properties = { 'couponModel_id_obj_ae' : _this.data('id'),
                                                                     'status' : 1};
                                            Dolphin.ajax({
                                                url: '/api/69c5ba08e23d493d89e421e41a898e6a',
                                                type: Dolphin.requestMethod.POST,
                                                data: Dolphin.json2string(paramData),
                                                onSuccess: function (reData) {
                                                    console.log(reData);
                                                    Dolphin.alert(reData.value.properties.msg);
                                                    me._dataList.load();
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    });
                }
            });
        },
        couponList: function (panelId, edit) {
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                columns: [{
                    code: 'id',
                    hidden: true,
                    title: '数据主键'
                }, {
                    code: 'name',
                    title: '券名称'
                }, {
                    code: 'code',
                    title: '券编码'
                },{
                    code: 'couponType',
                    title: '券类型',
                    formatter: function(val, row, index){
                        return Dolphin.enum.getEnumText("couponType", val);
                    }
                },{
                    code: 'couponVal',
                    title: '券优惠',
                    formatter: function(val, row, index){
                        if(row.couponType == 'CT01'){
                            return val + '元';
                        }else if(row.couponType == 'CT02'){
                            return val + '%';
                        }else{
                            return '无';
                        }
                    }
                }, {
                    code: 'status',
                    title: '状态',
                    formatter: function (val, row, index) {

                        var result = '';
                        // 0过期 1可用 2被领用 3已使用
                        if (val == 1) {
                            result = '未领用';
                        } else if(val == 2){
                            result = '已领用';
                        } else if(val == 3){
                            result = '已使用';
                        }else {
                            result = '已过期';
                        }
                        return result;

                    }
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '90px',
                    formatter: function (val, row, index) {
                        //操作按钮，如果可用状态，则可发给指定会员，否则隐藏
                        var diliveryBtnStr = '';
                        if(row.status == 1){
                            var diliveryBtnStr = '<a class="btn btn-outline btn-circle btn-sm green diliveryOneBtn" ' +
                                'href="javascript:;" data-id="'+row.id+'" >' +
                                '<i class="fa fa-paper-plane"></i>发放</a>';
                        }
                        return  diliveryBtnStr;
                    }
                }],
                multiple: false,
                rowIndex: false,
                checkbox: false,
                editFlag: edit,
                data: {rows: []},
                pagination: false,
                onClick: function (data, thisRow, event) {

                },
                onLoadSuccess: function () {
                    //发放券给某个会员
                    $(".diliveryOneBtn").click(function(){
                        var _this = $(this);
                        $("#couponId").val(_this.data('id'));
                        $('#userModal').modal('show');
                    });
                }

            });
        },
        initCouponStaticsList: function () {
            let me = this;
            me._couponStaticsList = new Dolphin.LIST({
                panel: "#couponStaticsList",
                title:'券',
                idField: 'id',
                columns: [{
                    code: 'id',
                    hidden: true,
                    title: '数据主键'
                }, {
                    code: 'name',
                    title: '券名称'
                }, {
                    code: 'code',
                    title: '券编码'
                },{
                    code: 'couponType',
                    title: '券类型',
                    formatter: function(val, row, index){
                        return Dolphin.enum.getEnumText("couponType", val);
                    }
                },{
                    code: 'couponVal',
                    title: '券优惠',
                    formatter: function(val, row, index){
                        if(row.couponType == 'CT01'){
                            return val + '元';
                        }else if(row.couponType == 'CT02'){
                            return val + '%';
                        }else{
                            return '无';
                        }
                    }
                }, {
                    code: 'status',
                    title: '状态',
                    formatter: function (val, row, index) {

                        var result = '';
                        // 0过期 1可用 2被领用 3已使用
                        if (val == 1) {
                            result = '未领用';
                        } else if(val == 2){
                            result = '已领用';
                        } else if(val == 3){
                            result = '已使用';
                        }else {
                            result = '已过期';
                        }
                        return result;

                    }
                }, {
                    code: 'userInfo',
                    title: '会员'
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/7fe370d66066418f88d4ea7db1896b2e',
                pagination: true,
                onClick: function (data, thisRow, event) {
                },
                onLoadSuccess: function () {
                }
            });
        },
        initUserList: function () {
            let me = this;
            me._userList = new Dolphin.LIST({
                panel: "#userList",
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: '会员名称'
                }, {
                    code: 'code',
                    title: '会员编码'
                }, {
                    code: 'phone',
                    title: '联系方式'
                }, {
                    code: 'idCard',
                    title: '身份证号'
                }, {
                    code: 'sex',
                    title: '性别',
                    formatter: function (val) {
                        return val;
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                pagination: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/8f7def63cc5845468b2c65a69abb0664',
                onLoadSuccess: function () {

                }
            });
        },

        /**
         * 一些页面DOM对象和事件的销毁
         */
        destroy: function () {

        }
    };
});